using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PowerUpSpawner : MonoBehaviour
{
    [Header("生成设置")]
    public GameObject[] powerUpPrefabs;
    public float baseSpawnRate = 8f; // 基础生成间隔（秒）
    public float spawnRateVariation = 2f; // 生成间隔变化范围
    public int maxPowerUpsOnScreen = 3;
    
    [Header("生成区域")]
    public float spawnHeight = 6f;
    public float spawnWidth = 8f;
    public Vector2 spawnCenter = Vector2.zero;
    
    [Header("道具配置")]
    public PowerUpConfig[] powerUpConfigs;
    
    [Header("生成概率")]
    public AnimationCurve spawnProbabilityCurve = AnimationCurve.Linear(0, 0.3f, 1, 1f);
    public float gameTimeForMaxProbability = 30f;
    
    [Header("调试设置")]
    public bool showDebugInfo = true;
    public bool showSpawnArea = true;
    
    private float nextSpawnTime;
    private Transform powerUpContainer;
    private float gameStartTime;
    
    [System.Serializable]
    public class PowerUpConfig
    {
        public PowerUpController.PowerUpType type;
        public GameObject prefab;
        public float spawnWeight = 1f;
        public float minGameTime = 0f; // 最早出现时间
        public float effectDuration = 10f;
        public float effectStrength = 1.5f;
        public PowerUpController.MovementPattern movementPattern = PowerUpController.MovementPattern.StraightDown;
        public Color powerUpColor = Color.yellow;
        public bool isRare = false; // 是否为稀有道具
    }
    
    void Start()
    {
        gameStartTime = Time.time;
        
        // 创建道具容器
        GameObject container = GameObject.Find("PowerUps");
        if (container == null)
        {
            container = new GameObject("PowerUps");
        }
        powerUpContainer = container.transform;
        
        // 设置初始生成时间
        ScheduleNextSpawn();
        
        Debug.Log($"道具生成器已初始化: 基础生成间隔={baseSpawnRate}s, 最大道具数={maxPowerUpsOnScreen}");
    }
    
    void Update()
    {
        if (Time.time >= nextSpawnTime)
        {
            TrySpawnPowerUp();
            ScheduleNextSpawn();
        }
        
        if (showDebugInfo)
        {
            int currentPowerUpCount = powerUpContainer.childCount;
            float gameTime = Time.time - gameStartTime;
            Debug.Log($"道具数量: {currentPowerUpCount}/{maxPowerUpsOnScreen}, 游戏时间: {gameTime:F1}s, 下次生成: {nextSpawnTime - Time.time:F1}s");
        }
    }
    
    void ScheduleNextSpawn()
    {
        float variation = Random.Range(-spawnRateVariation, spawnRateVariation);
        float spawnInterval = baseSpawnRate + variation;
        
        // 根据游戏时间调整生成频率
        float gameTime = Time.time - gameStartTime;
        float timeMultiplier = Mathf.Lerp(1f, 0.6f, gameTime / gameTimeForMaxProbability);
        spawnInterval *= timeMultiplier;
        
        nextSpawnTime = Time.time + Mathf.Max(2f, spawnInterval);
    }
    
    void TrySpawnPowerUp()
    {
        // 检查屏幕上道具数量
        if (powerUpContainer.childCount >= maxPowerUpsOnScreen)
        {
            if (showDebugInfo)
            {
                Debug.Log("屏幕道具数量已达上限，跳过生成");
            }
            return;
        }
        
        // 根据游戏时间计算生成概率
        float gameTime = Time.time - gameStartTime;
        float spawnProbability = spawnProbabilityCurve.Evaluate(gameTime / gameTimeForMaxProbability);
        
        if (Random.Range(0f, 1f) > spawnProbability)
        {
            if (showDebugInfo)
            {
                Debug.Log($"生成概率检查失败: {spawnProbability:F2}");
            }
            return;
        }
        
        // 选择要生成的道具类型
        PowerUpConfig selectedConfig = SelectPowerUpConfig(gameTime);
        if (selectedConfig != null)
        {
            SpawnPowerUp(selectedConfig);
        }
    }
    
    PowerUpConfig SelectPowerUpConfig(float gameTime)
    {
        // 筛选可用的道具配置
        List<PowerUpConfig> availableConfigs = new List<PowerUpConfig>();
        
        foreach (var config in powerUpConfigs)
        {
            if (gameTime >= config.minGameTime)
            {
                availableConfigs.Add(config);
            }
        }
        
        if (availableConfigs.Count == 0)
        {
            return null;
        }
        
        // 根据权重选择道具
        float totalWeight = 0f;
        foreach (var config in availableConfigs)
        {
            // 稀有道具权重随时间增加
            float weight = config.spawnWeight;
            if (config.isRare)
            {
                weight *= Mathf.Lerp(0.1f, 1f, gameTime / gameTimeForMaxProbability);
            }
            totalWeight += weight;
        }
        
        float randomValue = Random.Range(0f, totalWeight);
        float currentWeight = 0f;
        
        foreach (var config in availableConfigs)
        {
            float weight = config.spawnWeight;
            if (config.isRare)
            {
                weight *= Mathf.Lerp(0.1f, 1f, gameTime / gameTimeForMaxProbability);
            }
            
            currentWeight += weight;
            if (randomValue <= currentWeight)
            {
                return config;
            }
        }
        
        return availableConfigs[availableConfigs.Count - 1];
    }
    
    void SpawnPowerUp(PowerUpConfig config)
    {
        Vector3 spawnPosition = GetRandomSpawnPosition();
        
        GameObject powerUpObj;
        
        if (config.prefab != null)
        {
            powerUpObj = Instantiate(config.prefab, spawnPosition, Quaternion.identity, powerUpContainer);
        }
        else
        {
            // 创建默认道具对象
            powerUpObj = CreateDefaultPowerUp(config.type);
            powerUpObj.transform.position = spawnPosition;
            powerUpObj.transform.SetParent(powerUpContainer);
        }
        
        // 配置道具属性
        PowerUpController controller = powerUpObj.GetComponent<PowerUpController>();
        if (controller != null)
        {
            controller.powerUpType = config.type;
            controller.effectDuration = config.effectDuration;
            controller.effectStrength = config.effectStrength;
            controller.movementPattern = config.movementPattern;
            controller.powerUpColor = config.powerUpColor;
            
            // 根据配置调整移动参数
            if (config.movementPattern == PowerUpController.MovementPattern.SineWave)
            {
                controller.amplitude = Random.Range(1f, 2f);
                controller.frequency = Random.Range(1f, 3f);
            }
        }
        
        if (showDebugInfo)
        {
            Debug.Log($"生成道具: {config.type} 在位置 {spawnPosition}");
        }
    }
    
    Vector3 GetRandomSpawnPosition()
    {
        float randomX = Random.Range(-spawnWidth / 2f, spawnWidth / 2f);
        return new Vector3(spawnCenter.x + randomX, spawnCenter.y + spawnHeight, 0);
    }
    
    GameObject CreateDefaultPowerUp(PowerUpController.PowerUpType type)
    {
        GameObject powerUp = new GameObject($"PowerUp_{type}");
        
        // 添加控制器
        PowerUpController controller = powerUp.AddComponent<PowerUpController>();
        controller.powerUpType = type;
        
        return powerUp;
    }
    
    // 公共方法：设置生成速度
    public void SetSpawnRate(float rate)
    {
        baseSpawnRate = Mathf.Max(1f, rate);
        Debug.Log($"道具生成速度已设置为: {baseSpawnRate}s");
    }
    
    // 公共方法：获取当前道具数量
    public int GetCurrentPowerUpCount()
    {
        return powerUpContainer.childCount;
    }
    
    void OnDrawGizmos()
    {
        if (showSpawnArea)
        {
            // 绘制生成区域
            Gizmos.color = Color.magenta;
            Vector3 center = new Vector3(spawnCenter.x, spawnCenter.y + spawnHeight, 0);
            Vector3 size = new Vector3(spawnWidth, 0.5f, 0);
            Gizmos.DrawWireCube(center, size);
            
            // 绘制生成点示例
            Gizmos.color = Color.yellow;
            for (int i = 0; i < 3; i++)
            {
                Vector3 samplePos = GetRandomSpawnPosition();
                Gizmos.DrawWireSphere(samplePos, 0.3f);
            }
        }
    }
}